package org.aeon.client.view.components;

import lombok.extern.slf4j.Slf4j;
import org.aeon.client.context.GlobalContext;
import org.aeon.client.view.AccountUI;
import org.aeon.client.view.components.textField.MPasswordField;
import org.aeon.client.view.components.textField.MTextField;
import org.aeon.entity.User;
import org.aeon.message.request.CancelLoginRequestMessage;
import org.aeon.message.request.RegisterRequestMessage;
import org.aeon.utils.ImageSetUtil;
import org.aeon.utils.SimpleRequestUtil;
import org.aeon.utils.SwingUtil;

import javax.swing.*;
import java.awt.*;

import static org.aeon.client.context.MessageMap.MessageContextKey.RegisterMessage;


/**
 * @author: MissingAeon
 * @date: 2024/2/21 16:23
 * @description:
 */

@Slf4j
public class RegisterPanel extends JPanel {

    private final JLabel usernameWarning;
    private final JLabel passwordWarning;
    private final JLabel nicknameWarning;
    private final JLabel emailWarning;
    private final JLabel registerLabel;
    private final MTextField usernameField;
    private final MPasswordField passwordField;
    private final MTextField nicknameField;
    private final MTextField emailField;
    private final JButton registerBut;

    public RegisterPanel(JPanel parentPanel) {
        this.setLayout(new GridLayout(1, 2));
        this.add(AccountUI.logPanel());

        final JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createEmptyBorder(50, 10, 20, 10));

        final JLabel title = new JLabel("注册");
        title.setAlignmentX(Component.CENTER_ALIGNMENT);
        title.setFont(new Font("黑体", Font.BOLD, 24));
        panel.add(title);

        panel.add(Box.createVerticalStrut(25));

        final Dimension preferredSize = new Dimension(250, 35);
        final ImageIcon imageIcon = new ImageIcon(ImageSetUtil.getImage("warning", 30, 30));

        final Box usernameBox = Box.createHorizontalBox();
        usernameBox.add(Box.createHorizontalStrut(45));
        usernameField = new MTextField("账号");
        SwingUtil.setSize(usernameField, preferredSize);
        usernameBox.add(usernameField);
        usernameBox.add(Box.createHorizontalStrut(10));
        usernameWarning = new JLabel(imageIcon);
        usernameWarning.setVisible(false);
        usernameBox.add(usernameWarning);
        usernameBox.add(Box.createHorizontalGlue());
        panel.add(usernameBox);

        panel.add(Box.createVerticalStrut(15));

        final Box passwordBox = Box.createHorizontalBox();
        passwordBox.add(Box.createHorizontalStrut(45));
        passwordField = new MPasswordField("密码");
        SwingUtil.setSize(passwordField, preferredSize);
        passwordBox.add(passwordField);
        passwordBox.add(Box.createHorizontalStrut(10));
        passwordWarning = new JLabel(imageIcon);
        passwordWarning.setVisible(false);
        passwordBox.add(passwordWarning);
        passwordBox.add(Box.createHorizontalGlue());
        panel.add(passwordBox);

        panel.add(Box.createVerticalStrut(15));

        final Box nicknameBox = Box.createHorizontalBox();
        nicknameBox.add(Box.createHorizontalStrut(45));
        nicknameField = new MTextField("昵称");
        nicknameField.setPreferredSize(preferredSize);
        nicknameField.setMaximumSize(preferredSize);
        nicknameField.setMinimumSize(preferredSize);
        nicknameBox.add(nicknameField);
        nicknameBox.add(Box.createHorizontalStrut(10));
        nicknameWarning = new JLabel(imageIcon);
        nicknameWarning.setVisible(false);
        nicknameBox.add(nicknameWarning);
        nicknameBox.add(Box.createHorizontalGlue());
        panel.add(nicknameBox);

        panel.add(Box.createVerticalStrut(15));

        final Box emailBox = Box.createHorizontalBox();
        emailBox.add(Box.createHorizontalStrut(45));
        emailField = new MTextField("邮箱");
        SwingUtil.setSize(emailField, preferredSize);
        emailBox.add(emailField);
        emailBox.add(Box.createHorizontalStrut(10));
        emailWarning = new JLabel(imageIcon);
        emailWarning.setVisible(false);
        emailBox.add(emailWarning);
        emailBox.setAlignmentX(Component.CENTER_ALIGNMENT);
        emailBox.add(Box.createHorizontalGlue());
        panel.add(emailBox);

        panel.add(Box.createVerticalStrut(25));

        registerBut = new JButton("注册");
        final Dimension dimensionBut = new Dimension(160, 30);
        SwingUtil.setSize(registerBut, dimensionBut);
        registerBut.setContentAreaFilled(false);
        registerBut.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(registerBut);


        panel.add(Box.createVerticalStrut(22));

        registerLabel = new JLabel("这是个注册提示");
        registerLabel.setForeground(new Color(0x0FFFFFF, true));
        registerLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(registerLabel);

        panel.add(Box.createVerticalStrut(12));

        final JPanel tmpP = new JPanel();
        tmpP.setLayout(new BoxLayout(tmpP, BoxLayout.X_AXIS));
        final JButton loginBut = new JButton("←登陆");
        loginBut.setAlignmentX(Component.RIGHT_ALIGNMENT);
        loginBut.setContentAreaFilled(false);
        tmpP.add(loginBut);
        loginBut.addActionListener(e -> {
            final CardLayout layout = (CardLayout) parentPanel.getLayout();
            layout.show(parentPanel, "LP");
            parentPanel.repaint();
        });
        tmpP.add(Box.createHorizontalGlue());
        panel.add(tmpP);
        this.add(panel);

        registerBut.addActionListener(e -> {
            registerBut.setEnabled(false);
            recoveryWarning();

            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());
            String nickname = nicknameField.getText();
            String email = emailField.getText();

            if (checkInput(username, password, nickname, email)) {
                setErrorMessage("请输入完整信息");
                return;
            }
            resetInputBox();

            GlobalContext context = GlobalContext.getContext();
            if (context.getChannel() != null) {
                RegisterRequestMessage reqMsg = new RegisterRequestMessage(new User(username, password, nickname, email));
                SimpleRequestUtil.sendAndWaitOrTimeout(context, reqMsg, this::handleRegisterSuccess,
                        () -> {
                            registerBut.setEnabled(true);
                            SimpleRequestUtil.send(context, new CancelLoginRequestMessage());
                        }, 10);
            } else setErrorMessage("无法连接到服务器");

        });
    }

    private void setErrorMessage(String message) {
        SwingUtilities.invokeLater(() -> {
            registerLabel.setText(message);
            registerLabel.setForeground(new Color(0xFF1616));
            registerBut.setEnabled(true);
        });
    }

    private void handleRegisterSuccess() {
        SwingUtilities.invokeLater(() -> {
            final GlobalContext context = GlobalContext.getContext();
            String registerMessage = context.getMessageMap().del(RegisterMessage);
            if (context.getIsLogin().get()) {
                registerLabel.setText(registerMessage);
                registerLabel.setForeground(new Color(0x414141));
                LoginPanel.successFuture(this).start();
            } else {
                setErrorMessage(registerMessage);
            }
        });
    }

    private void resetInputBox() {
        usernameField.setText("");
        passwordField.setText("");
        nicknameField.setText("");
        emailField.setText("");
    }

    private boolean checkInput(String username, String password, String nickname, String email) {
        if (username == null || username.isEmpty()) {
            showWarning(usernameWarning, "请输入用户名！");
            return true;
        }
        if (password.isEmpty()) {
            showWarning(passwordWarning, "请输入密码！");
            return true;
        }
        if (nickname == null || nickname.isEmpty()) {
            showWarning(nicknameWarning, "请输入昵称！");
            return true;
        }
        if (email == null || email.isEmpty()) {
            showWarning(emailWarning, "请输入邮箱！");
            return true;
        }
        return false;
    }

    private void showWarning(JLabel warningLabel, String message) {
        warningLabel.setToolTipText(message);
        warningLabel.setVisible(true);
    }

    private void recoveryWarning() {
        usernameWarning.setVisible(false);
        passwordWarning.setVisible(false);
        nicknameWarning.setVisible(false);
        emailWarning.setVisible(false);
    }
}
